package com.ma.chapter4.t8;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ByOrderOut
 * @Author: mayongqiang
 * @DATE 2022/3/16 20:23
 * @Description: 交替输出  p130  很漂亮的思路和代码，非常值得学习！
 */
@Slf4j(topic = "m.ByOrderOut")
public class ByOrderOut1 {
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1, 5);


        new Thread(() -> {
            try {
                wn.print("a", 1, 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                wn.print("b", 2, 3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();

        new Thread(() -> {
            try {
                wn.print("c", 3, 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t3").start();

    }
}

/*
输出内容    等待标记        下一个标记
  a         i=1             2
  b         i=2             3
  c         i=3             1
 */
class WaitNotify {

    //等待标记
    private int flag;
    //循环次数
    private int number;

    public WaitNotify(int flag, int number) {
        this.flag = flag;
        this.number = number;
    }

    //打印
    public void print(String str, int waitFlag, int nextFlag) throws InterruptedException {
        for (int i = 0; i < number; i++) {
            synchronized (this) {
                while (flag != waitFlag) {
                    this.wait();
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }

    }
}